/**   
 * @Title: ReqUtisl.java 
 * @Package com.enchantin.endzone.util 
 * @Description: TODO
 * @author weiwei
 * @date 2015-4-23 上午10:58:56 
 * @version V1.0   
 */
package com.yitong.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yitong.spring.reqcheck.exception.DataParserException;

/**
 * @author weiwei
 * @Date 2015-4-23
 */
public class ReqUtils {

	private static final Logger LOG = LoggerFactory.getLogger(ReqUtils.class);

	/**
	 * 获取请求json对象
	 * 
	 * @param reqType
	 *            请求参数类型
	 * @param request
	 *            http请求对象
	 * @return
	 * @throws IOException
	 */
	public static JSON getReqJson(HttpServletRequest request) throws DataParserException {
		String reqBody = "{}";
		try {
			reqBody = IOUtils.toString(request.getInputStream(), "UTF-8");
			if (LOG.isDebugEnabled()) {
				LOG.debug("request str is :" + reqBody);
			}
			if (StringUtils.isBlank(reqBody)) {
				reqBody = "{}";
			}
			return (JSON) JSON.parse(reqBody);
		} catch (Exception ex) {
			LOG.error("请求数据转换失败", ex);
			throw new DataParserException(ex.getMessage(), ex);
		}
	}

	/**
	 * @Title: writeError
	 * @Description: writeError
	 * @param code
	 * @param err
	 * @param msg
	 * @param response
	 * @return void
	 */
	public static void writeError(Integer code, String msg, HttpServletResponse response) {
		response.setContentType(ConstantUtils.CONTENT_TYPE_APPLICATION_JSON);
		JSONObject json = new JSONObject();
		json.put(ConstantUtils.CODE, code);
		json.put(ConstantUtils.MSG, msg);
		try {
			if (LOG.isDebugEnabled()) {
				LOG.debug("ret: " + json.toJSONString());
			}
			response.getWriter().print(json.toJSONString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
